﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CoolCode.DataSource.DB4O
{
   public   class CacheDataProvider:DataProvider 
    {
       //public static string GetPath<T>()
       //{
       //    string path= typeof(T).Name+"/";
       //    return path;
       //}

       //public static string GetPath<T>(int Index)
       //{
       //    return GetPath<T>() + Index + "/";
       //}

       public static string GetListPath<T>()
       {
           string path = typeof(T).Name + "List/";
           return path;
       }

       public override void Delete<T>(T TEntity)
       {
           var query = CacheFactory.CreateInstance().GetItem(GetListPath<T>()) as IList<T>;
           if (query != null)
               query.Remove(TEntity);
           base.Delete<T>(TEntity);
       }

       public override void DeleteAll<T>(IEnumerable<T> TList)
       {
           CacheFactory.CreateInstance().RemoveItem(GetListPath<T>());
           base.DeleteAll<T>(TList);
       }

       public override IList<T> Query<T>()
       {
           if (CacheFactory.CreateInstance().GetItem(GetListPath<T>()) == null)
           {
               var q=base.Query<T>();
              CacheFactory.CreateInstance().AddItem(GetListPath<T>(),q);
           }
           var query =CacheFactory.CreateInstance().GetItem(GetListPath<T>()) as IList<T> ;
           return query;
       }

       public override IList<T> Query<T>(Predicate<T> predicate)
       {
           if (CacheFactory.CreateInstance().GetItem(GetListPath<T>()) == null)
           {
               return base.Query<T>(predicate);
           }
           var query = CacheFactory.CreateInstance().GetItem(GetListPath<T>()) as IList<T>;
           return query.Where<T>( c=> predicate(c)).ToList();
       }

       public override void Store<T>(T TEntity)
       {
           CacheFactory.CreateInstance().RemoveItem(GetListPath<T>());
           base.Store<T>(TEntity);
       }

       public override void StoreAll<T>(IEnumerable<T> TList)
       {
           CacheFactory.CreateInstance().RemoveItem(GetListPath<T>());
           base.StoreAll<T>(TList);
       }

       public override bool Contains<T>(Predicate<T> predicate)
       {
           var query = CacheFactory.CreateInstance().GetItem(GetListPath<T>()) as IList<T>;
           if (query != null)
               return query.Where(c => predicate(c)).Count() > 0;
           return base.Contains<T>(predicate);
       }

    }
}
